package me.leoray.leilog;

import android.util.Log;

/**
 * 调用系统api控制台输出,参考: {@link Log}
 * Created by leoraylei on 16/8/28.
 */
public class ConsolePipeLine extends AbstractPipeLine {

    private static final int CHUNK_SIZE = 4000; //保证控制台信息打印完整

    @Override
    public ConsolePipeLine level(int level) {
        super.level(level);
        return this;
    }

    @Override
    public ConsolePipeLine setLogProxy(LogProxy proxy) {
        super.setLogProxy(proxy);
        return this;
    }

    @Override
    public void log(int logType, String tag, String message, Throwable t) {
        if (message == null || message.length() < CHUNK_SIZE) {
            logIt(logType, tag, message + (t != null ? ('\n' + Log.getStackTraceString(t)) : ""));
        } else {
            int start = 0;
            int end = Math.min(message.length(), start + CHUNK_SIZE);
            while (end <= message.length() && start < end) {
                logIt(logType, tag, message.substring(start, end));
                start = end;
                end = Math.min(message.length(), start + CHUNK_SIZE);
            }
            if (t != null) {
                logIt(logType, tag, Log.getStackTraceString(t));
            }
        }
    }

    private void logIt(int logType, String tag, String message) {
        switch (logType) {
            case Log.VERBOSE:
                Log.v(tag, message);
                break;
            case Log.DEBUG:
                Log.d(tag, message);
                break;
            case Log.INFO:
                Log.i(tag, message);
                break;
            case Log.WARN:
                Log.w(tag, message);
                break;
            case Log.ERROR:
                Log.e(tag, message);
                break;
            case Log.ASSERT:
                Log.wtf(tag, message);
                break;
            default:
                Log.d(tag, message);
        }
    }
}
